package com.x.compute.common.function;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.util.Date;
import java.util.Map;

/**
 * 日期格式转换函数
 * 函数示例：DATE(date, format)
 * @author xuxin
 */
public class DateFunction extends AbstractFunction {

    @Override
    public String getName() {
        return "DATE";
    }

    /**
     * 函数处理逻辑
     * @param env 变量上下文
     * @param arg1 日期字符串，格式 yyyy-MM-dd HH:mm:ss
     * @param arg2 日期转换格式
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        String dateString = getDateString(arg1, env);
        DateTime dateTime = DateTime.of(dateString, DatePattern.NORM_DATE_PATTERN);
        String format = FunctionUtils.getStringValue(arg2, env);
        String value = dateTime.toString(format);
        if (NumberUtil.isNumber(value)){
            value = Integer.valueOf(value).toString();
        }
        return new AviatorString(value);
    }

    /**
     * 获取日期字符串
     * @param arg1
     * @param env
     * @return
     */
    private String getDateString(AviatorObject arg1, Map<String, Object> env){
        Object object = FunctionUtils.getJavaObject(arg1, env);
        if (object instanceof Character) {
            return object.toString();
        } else if (object instanceof Date){
            return DateUtil.formatDateTime((Date) object);
        }else {
            return (String)object;
        }
    }

}
